package edu.mju.controller;

import com.alibaba.fastjson.JSONObject;
import edu.mju.dao.IScenicSpotDao;
import edu.mju.dao.impl.ScenicSpotDaoImpl;
import edu.mju.entity.ScenicSpot;
import edu.mju.service.ISpotListService;
import edu.mju.service.impl.SpotListServiceImpl;
import edu.mju.util.FileUtil;
import edu.mju.util.Pager;
import edu.mju.util.RequestStrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author:wyp
 * @Date:2020/5/16 17:35
 */
@WebServlet("/spotController")
public class SpotController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        //获取method
        String method = req.getParameter("method");

        System.out.println("doget:"+method);
        if("allSpot".equals(method)){
            //对应backindex.jsp的所有景点按钮
            req.getRequestDispatcher("/WEB-INF/view/backindex/spot-list.jsp").forward(req,resp);
        }else if("spotAdd".equals(method)){
            req.getRequestDispatcher("/WEB-INF/view/backindex/spot-add.jsp").forward(req,resp);
        }else if("spotById".equals(method)){
            //对应spot-list.jsp的编辑景点按钮
            String spotId = req.getParameter("spotId");
            req.getRequestDispatcher("/WEB-INF/view/backindex/spot-edit.jsp?spotId="+spotId).forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        //获取method
        String method = req.getParameter("method");
        System.out.println("dopost:"+method);
        if("allSpot".equals(method)){
            //对应spotList的页面载入
            pagernate(req, resp);
        }else if("spotAdd".equals(method)){
            //对应spot-add.jsp 的景点添加
            spotAdd(req,resp);
        }else if("spotById".equals(method)){
            //对应spot-edit.jsp 的数据显示
            spotById(req, resp);
        }else if("spotDel".equals(method)){
            //对应spot-list.jsp 的数据删除
            spotDel(req,resp);
        }else if("spotUpdate".equals(method)){
            //对应spot-edit.jsp 的数据更新
            spotUpdate(req,resp);
        }else if("searchSpot".equals(method)){
            pagernate(req, resp);
        }else if("showSpot".equals(method)){
            //对应routesDatail.jsp的ajax请求
            showSpot(req,resp);
        }else if("spotDetail".equals(method)){
            //对应spotDatail.jsp的ajax请求
            showSpotDetail(req,resp);
        }
    }
    private void showSpotDetail(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        Integer spotId = Integer.valueOf(req.getParameter("spotId"));
        ScenicSpot scenicSpot = new ScenicSpot();

        ISpotListService spotListService = new SpotListServiceImpl();
        scenicSpot = spotListService.findBySpotId(spotId);

        String result = JSONObject.toJSONString(scenicSpot);
        System.out.println("showSpot的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("showSpot跳转失败！");
            e.printStackTrace();
        }
    }


    private void showSpot(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");

        ScenicSpot scenicSpot = new ScenicSpot();

        ISpotListService spotListService = new SpotListServiceImpl();
        List<ScenicSpot> list = spotListService.findAll();

        String result = JSONObject.toJSONString(list);
        System.out.println("showSpot的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("showSpot跳转失败！");
            e.printStackTrace();
        }
    }

    /**
     *  更新景点数据
     * @param req
     * @param resp
     */
    private void spotUpdate(HttpServletRequest req, HttpServletResponse resp){
        Integer spotId = Integer.valueOf(req.getParameter("spotId"));
        String spotName = req.getParameter("spotName");
        String spotPlace = req.getParameter("spotPlace");
        String spotItem = req.getParameter("spotItem");
        Integer spotPrice = Integer.valueOf(req.getParameter("spotPrice"));
        String spotOpenTime = req.getParameter("spotOpenTime");
        String spotImgUrl = req.getParameter("spotImgUrl");

        ScenicSpot scenicSpot = new ScenicSpot(spotId,spotName,spotPlace,spotItem,spotPrice,spotOpenTime,spotImgUrl);
        ISpotListService spotListService = new SpotListServiceImpl();
        try {
            if(spotListService.update(scenicSpot)){
                String rs = JSONObject.toJSONString(scenicSpot);
                resp.getWriter().write(rs);
            }else {
                resp.getWriter().write("false");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    /**
     *  删除景点
     * @param req
     * @param resp
     */
    private void spotDel(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Integer spotId = RequestStrUtil.getValue(req.getParameter("delspotId"),0);

            System.out.println(spotId);
            IScenicSpotDao scenicSpotDao = new ScenicSpotDaoImpl();
            boolean delPot = scenicSpotDao.delete(spotId);
            if(delPot) {
                //删除图片
                String imgUrl = req.getParameter("imgUrl");
                String delPath = this.getServletContext().getRealPath(imgUrl);
                FileUtil.deleteFile(delPath);

                String result = JSONObject.toJSONString(delPot);
                System.out.println(result);
                resp.getWriter().write(result);
            }else {
                //只要返回的不是json格式，ajax执行error
                resp.getWriter().write("添加失败，景点已存在！");
            }

        }catch (Exception e){
            System.out.println("spotAdd方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *  景点展示 根据景点ID
     * @param req
     * @param resp
     */
    private void spotById(HttpServletRequest req, HttpServletResponse resp){

        Integer spotId = Integer.valueOf(req.getParameter("spotId"));
        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");

        ISpotListService spotListService = new SpotListServiceImpl();
        ScenicSpot scenicSpot = spotListService.findBySpotId(spotId);
        String result = JSONObject.toJSONString(scenicSpot);

        try {
            System.out.println(result);
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("spotEdit方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *      分页查询所有景点信息
     * @param req
     * @param resp
     */
    public void pagernate(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        //每页显示数据
        int pageSize = 5 ;
        String getPageSize = req.getParameter("pageSize");
        if(getPageSize!=null && !"".equals(getPageSize)){

            pageSize= Integer.parseInt(getPageSize);
        }
        //设定默认当前页码数
        int page = 1;
        String getSearch = req.getParameter("searchName");

        String getPage = req.getParameter("page");
        if(getPage !=null && ! "".equals(getPage)){
            page = (Integer.valueOf(getPage)) ;
        }

        ScenicSpot scenicSpot = new ScenicSpot();
        scenicSpot.setSpotName(getSearch);
        System.out.println("pagenate1:"+getSearch);

        ISpotListService spotListService = new SpotListServiceImpl();
        Pager pager = spotListService.pagernate(page,pageSize,scenicSpot);
        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *  添加景点
     * @param req
     * @param resp
     */
    private void spotAdd(HttpServletRequest req, HttpServletResponse resp){
        try {

        String spotName=req.getParameter("spotName");
        String spotPlace=req.getParameter("spotPlace");
        String spotItem = req.getParameter("spotItem");
        Integer spotPrice = Integer.valueOf(req.getParameter("spotPrice"));
        String spotOpenTime = req.getParameter("spotOpenTime");
        String spotImgUrl = req.getParameter("spotImgUrl");


        ScenicSpot inspot = new ScenicSpot(spotName,spotPlace,spotItem,spotPrice,spotOpenTime,spotImgUrl);
        IScenicSpotDao scenicSpotDao = new ScenicSpotDaoImpl();
        boolean reuser = scenicSpotDao.insert(inspot);
        if(reuser) {
            String result = JSONObject.toJSONString(inspot);
            System.out.println(result);
            resp.getWriter().write(result);
        }else {
            //只要返回的不是json格式，ajax执行error
            resp.getWriter().write("添加失败，景点已存在！");
        }

        }catch (Exception e){
            System.out.println("spotAdd方法跳转失败：");
            e.printStackTrace();
        }
    }
}
